package com.msdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.msdp.entity.Shop;
import com.msdp.service.IShopService;
import com.msdp.service.impl.ShopServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.msdp.utils.RedisConstants.*;
import static com.msdp.utils.RedisConstants.CACHE_SHOP_TTL;

@Component
@Slf4j
public class RedisUtils {

    private final StringRedisTemplate stringRedisTemplate;

    private IShopService shopService;
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public RedisUtils(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void  set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }



    /**
     * 根据id查询信息(缓存穿透)
     * @param id
     * @return
     */
    public <R, ID> R queryShopByIdWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID, R> dbCallback, Long time, TimeUnit unit
    ) {
        // 1. 从Redis中查询商铺缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        // 2.判断缓存是否命中
        if (StrUtil.isNotBlank(json)) {
            // 3.命中后判断是否为空
            return JSONUtil.toBean(json, type);
        }
        // 判断命中的是否是空值
        if(json != null){
            return null;
        }
        // 4.未命中->根据id查询数据库
        R r = dbCallback.apply(id);

        // 5.判断商户是否存在
        if (r == null) {
            // 5.1不存在->缓存null值解决缓存穿透问题
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            // 5.2返回404
            return null;
        }

        // 6.存在->将数据写入Redis
        json = JSONUtil.toJsonStr(r);
        this.set(key, json, time, unit);

        // 7.返回商铺信息
        return r;
    }


    /**
     * 根据id查询商铺信息(互斥锁解决缓存击穿)
     * @param id
     * @return
     */
    public Shop queryShopByIdMutex(Long id) {
        // 1. 从Redis中查询商铺缓存
        String key = CACHE_SHOP_KEY + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        // 2.判断缓存是否命中
        if (StrUtil.isNotBlank(json)) {
            // 3.命中后判断是否为空
            return JSONUtil.toBean(json, Shop.class);
        }
        // 判断命中的是否是空值
        if(json != null){
            return null;
        }
        // 4.未命中->
        // 4.1 获取互斥锁
        Shop shop = null;
        String lockKey =  LOCK_SHOP_KEY + id;
        try {

            boolean flag = tryLock(lockKey);
            if(!flag){
                // 4.2 获取失败
                Thread.sleep(50);
                return queryShopByIdMutex(id);
            }
            // 4.3 获取成功-> 根据id查询数据库
            shop = shopService.getById(id);
            // 模拟延时重建
            Thread.sleep(200);
            // 5.判断商户是否存在
            if (shop == null) {
                // 5.1不存在->缓存null值解决缓存穿透问题
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                // 5.2返回404
                return null;
            }

            // 6.存在->将数据写入Redis
            json = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(key, json, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            unLock(lockKey);
        }
        // 7.返回商铺信息
        return shop;
    }


    /**
     * 根据id查询商铺信息(逻辑过期解决缓存击穿)
     * @param id
     * @return
     */
    public <R, ID> R queryLogicalExpire(
            String ketPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit
            ) {
        // 1. 从Redis中查询商铺缓存
        String key = ketPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        // 2.判断缓存是否命中
        if (StrUtil.isBlank(json)) {
            // 3.未命中返回空
            return null;
        }

        // 4.命中->先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5. 判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())) {
            //5.1 未过期，直接返回店铺信息
            return r;
        }
        //5.2 已过期，需要缓存重建
        //6. 缓存重建
        //6.1 获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        //6.2 判断是否获取锁成功
        if(isLock){
            //6.3 成功开启独立线程实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    R r1 = dbFallback.apply(id);
                    Thread.sleep(200);
                    this.setWithLogicalExpire(key, r1, time, unit);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });
        }
        //6.4 返回过期的商铺信息
        return r;
    }

    /**
     * 获取锁
     * @param key
     * @return
     */
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    /**
     * 释放锁
     * @param key
     * @return
     */
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }


}
